package com.dcy.daily.common.aspect;

import com.dcy.daily.common.dataSource.DynamicDataSource;
import com.dcy.daily.common.utils.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;


/**
 * @author duanchunyu
 * @version 1.0.0
 * @createTime 2021年05月28日 14:58:00
 */
@Aspect
@Component
public class DataSourceAspect {

    @Pointcut("@annotation(com.dcy.daily.common.aspect.TargetDataSource)"
            +"@within(com.dcy.daily.common.aspect.TargetDataSource)")
    public void PointCut(){}

    @Around("PointCut()")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable{
        MethodSignature methodSignature = (MethodSignature) proceedingJoinPoint.getSignature();
        Method method = methodSignature.getMethod();
        TargetDataSource dataSource = method.getAnnotation(TargetDataSource.class);
        if(StringUtils.isNotNull(dataSource)){
            DynamicDataSource.setDataSourceKey(dataSource.value());
        }
        try {
           return proceedingJoinPoint.proceed();
        } finally {
            DynamicDataSource.clearDataSourceKey();
        }
    }
}
